// pages/release-sellshop/release-sellshop.js

import { Shop } from '../../models/shop'
import { check } from '../../util/identityCheck'
import { Publish } from '../../models/other'
import locationList from '../../util/area'
const publishModel = new Publish()
const shopModel = new Shop()

import UploadImg from '../../util/uploadImg'
const uploadImg = new UploadImg()

import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog'
function getShareId() {
  const shareId = wx.getStorageSync('otherId')
  if (shareId && shareId != 'undefined') {
    // 注意 这里是字符串类型的undefined 好奇我为什么没封装一下？因为我真的很忙
    return shareId
  } else {
    return ''
  }
}
Page({
  data: {
    locationList,
    showPopup: {
      district: false,
      transferWay: false,
      advantage: false,
      location: false,
      area: false
    },
    id: null,
    transferWayList: [],
    districtList: [],
    transferFeeType: '0',
    advantageList: [],
    areaList: [],
    Shop: {
      shareUserId: '',
      avatar: '',
      title: '',
      contactName: '',
      contactPhone: '',
      district: '',
      area: '',
      transferWay: '',
      location: '',
      address: '',
      advantage: '',
      shopEnvironmentList: [],
      shopEnvironment: '',
      transferFee: '',
      rentFee: ''
    }
  },

  onShow() {
    const shareUserId = getShareId()
    setTimeout(() => {
      this.setData({
        'Shop.shareUserId': shareUserId
      })
    }, 1000)
    if (!check()) return
  },

  onLoad(options) {
    this.setData({
      id: options.id
    })
    if (+options.id) {
      this.getDetail()
    } else {
      this.getDraft()
    }
  },

  getDetail() {
    // 编辑时获取详情
    shopModel.sellShopDetail(
      {
        id: this.data.id
      },
      (res) => {
        wx.hideLoading()
        if (res.transferFee == '面议') {
          this.setData({
            transferFeeType: '1',
            Shop: { shopEnvironmentList: [], ...res }
          })
        } else {
          res.transferFee = res.transferFee.replace(/万元/, '')
          this.setData({
            Shop: { shopEnvironmentList: [], ...res }
          })
        }
        if (res.auditStatus == 2) {
          Dialog.alert({
            title: '审核未通过',
            message: `未通过原因：${res.remark} \n 请重新修改并提交审核。`
          }).then(() => {
            // on close
          })
        }
        if (res.auditStatus == 3) {
          Dialog.alert({
            message: `下架原因：${res.remark} \n 如需继续使用请重新付费发布！`
          }).then(() => {
            // on close
          })
        }
      }
    )
  },

  onChangeTransferFeeType(e) {
    // 切换转让费类型
    this.setData({
      transferFeeType: e.detail,
      'Shop.transferFee': ['', '面议'][e.detail]
    })
  },

  chooseImage() {
    uploadImg.chooseImg(5, (res) => {
      let imgList = this.data.Shop.shopEnvironmentList
      imgList.push(res)
      this.setData({
        'Shop.shopEnvironmentList': imgList,
        'Shop.shopEnvironment': imgList.join(',')
      })
    })
  },

  chooseLocation() {
    let that = this
    wx.chooseLocation({
      success(res) {
        that.setData({
          'Shop.address': res.name
        })
      }
    })
  },

  publish() {
    let Shop = this.data.Shop
    if (!Shop.avatar) {
      wx.showToast({
        title: '请上传封面图片',
        icon: 'none'
      })
      return
    }
    if (!Shop.title) {
      wx.showToast({
        title: '请填写卖店标题',
        icon: 'none'
      })
      return
    }
    if (!Shop.district) {
      wx.showToast({
        title: '请选择地段信息',
        icon: 'none'
      })
      return
    }
    if (!Shop.area) {
      wx.showToast({
        title: '请填写店铺面积',
        icon: 'none'
      })
      return
    }
    if (!Shop.transferWay) {
      wx.showToast({
        title: '请选择转让方式',
        icon: 'none'
      })
      return
    }
    if (!Shop.transferFee) {
      wx.showToast({
        title: '请填写转让费用',
        icon: 'none'
      })
      return
    }
    if (!Shop.rentFee) {
      wx.showToast({
        title: '请填写租金',
        icon: 'none'
      })
      return
    }
    if (!Shop.location) {
      wx.showToast({
        title: '请选择所在区域',
        icon: 'none'
      })
      return
    }
    if (!Shop.address) {
      wx.showToast({
        title: '请填写详细地址',
        icon: 'none'
      })
      return
    }
    if (!Shop.advantage) {
      wx.showToast({
        title: '请选择店铺优势',
        icon: 'none'
      })
      return
    }
    if (!Shop.contactName) {
      wx.showToast({
        title: '请填写联系人',
        icon: 'none'
      })
      return
    }
    if (/^[0-9]*$/.test(Shop.contactName)) {
      wx.showToast({
        title: '联系人不可以是数字',
        icon: 'none'
      })
      return
    }
    if (!Shop.contactPhone) {
      wx.showToast({
        title: '请填写联系电话',
        icon: 'none'
      })
      return
    }
    if (!Shop.shopEnvironmentList.length) {
      wx.showToast({
        title: '请上传店铺照片',
        icon: 'none'
      })
      return
    }
    if (Shop.contactPhone.includes('*')) {
      delete Shop.contactPhone
    }
    if (this.data.transferFeeType == '0') {
      Shop.transferFee += '万元'
    }
    this.removeDraft()
    shopModel.publishSellShop(Shop, (res) => {})
    wx.navigateTo({
      url: `/pages/pay-join/pay-join?type=卖店&data=${JSON.stringify(Shop)}`
    })
  },

  update() {
    let Shop = this.data.Shop
    Dialog.confirm({
      message: '更新后需再次审核\n 是否确认更新？'
    }).then(() => {
      if (this.data.transferFeeType == '0') {
        Shop.transferFee += '万元'
      }
      if (Shop.contactPhone.includes('*')) {
        delete Shop.contactPhone
      }

      shopModel.update(Shop, (res) => {
        Dialog.alert({
          title: '更新成功！',
          message: `平台将在24小时内完成审核，请耐心等待！`
        }).then(() => {
          wx.requestSubscribeMessage({
            tmplIds: [
              '-DHKrW9DRvbg3sEoVRYtcRxRyr-kYzyTN-9BNCY89rI',
              'b7FIjt52cUMvTClpMJKJLe8lzi4rnQsWlUc7D5VYGoA',
              'PbmE0p7hgtUXlZcUEgR_qBcP3tMhbe1-_wKNw7CkoZY'
            ],
            complete(res) {
              wx.navigateBack()
            }
          })
        })
      })
    })
  },

  confirmDialogTip() {
    wx.navigateBack({
      delta: 1
    })
  },

  onReady() {
    this.init()
  },

  inputChange(evevt) {
    let key = `Shop.${evevt.currentTarget.dataset.type}`
    if (
      key == 'Shop.area' ||
      key == 'Shop.contactPhone' ||
      key == 'Shop.transferFee'
    ) {
      evevt.detail = evevt.detail
        .replace(/[^\d^\.]+/g, '')
        .replace('.', '$#$')
        .replace(/\./g, '')
        .replace('$#$', '.')
    }
    this.setData({
      [key]: evevt.detail
    })
  },

  onDateInput(event) {
    this.setData({
      currentDate: event.detail
    })
  },

  uploadCover() {
    uploadImg.chooseImg(1, (imgUrl) => {
      this.setData({
        'Shop.avatar': imgUrl
      })
    })
  },

  onShowPopup(e) {
    // 打开弹窗
    wx.hideKeyboard()
    const which = e.currentTarget.dataset.key
    const key = `showPopup.${which}`
    this.setData({
      [key]: true
    })
  },

  onClosePopup() {
    // 关闭弹窗
    for (let key in this.data.showPopup) {
      key = `showPopup.${key}`
      this.setData({
        [key]: false
      })
    }
  },

  onDistrict(e) {
    // 选择地段
    console.log(e)
    this.setData({
      'Shop.district': e.detail
    })
  },

  onTransferWay(e) {
    // 选择转让方式
    this.setData({
      'Shop.transferWay': e.detail
    })
  },
  onArea(e) {
    // 选择店铺面积
    this.setData({
      'Shop.area': e.detail.selected
    })
  },

  onAdvantage(e) {
    // 选择店铺优势
    this.setData({
      'Shop.advantage': e.detail
    })
  },

  onAreaConfirm(e) {
    const location = e.detail.values
    this.setData({
      'Shop.location': location[0].name + location[1].name + location[2].name,
      'showPopup.location': false
    })
  },

  onAreaCancel(e) {
    this.setData({
      'showPopup.location': false
    })
  },

  getDistrictList() {
    // 获取商铺地段
    publishModel.getPublicTypes(
      {
        tagKey: '商铺地段',
        type: 1
      },
      (res) => {
        this.setData({
          districtList: res
        })
      }
    )
  },

  getTransferWay() {
    // 获取转让方式
    publishModel.getPublicTypes(
      {
        tagKey: '转让方式',
        type: 1
      },
      (res) => {
        this.setData({
          transferWayList: res
        })
      }
    )
  },

  getAdvantageList() {
    // 获取店铺优势
    publishModel.getPublicTypes(
      {
        tagKey: '商铺优势',
        type: 1
      },
      (res) => {
        this.setData({
          advantageList: res
        })
      }
    )
  },

  getArea() {
    // 获取商铺面积
    publishModel.getPublicTypes(
      {
        tagKey: '商铺面积',
        type: 1
      },
      (res) => {
        this.setData({
          areaList: res
        })
      }
    )
  },

  removeImg(e) {
    const index = e.currentTarget.dataset.index
    let imgList = this.data.Shop.shopEnvironmentList
    imgList.splice(index, 1)
    this.setData({
      'Shop.shopEnvironmentList': imgList,
      'Shop.shopEnvironment': imgList.join(',')
    })
  },

  delete() {
    Dialog.confirm({
      message: '删除后信息将不再展示，且不可恢复！\n 是否确认删除？'
    }).then(() => {
      shopModel.deleteSellShop(
        {
          id: this.data.id
        },
        (res) => {
          wx.showToast({
            title: '删除成功',
            icon: 'none'
          })
          wx.navigateBack({
            delta: 1
          })
        }
      )
    })
  },

  saveDraft() {
    wx.setStorageSync('sellShopData', this.data.Shop)
    wx.showToast({
      title: '草稿保存成功！'
    })
  },

  getDraft() {
    const Shop = wx.getStorageSync('sellShopData') || this.data.Shop
    this.setData({
      Shop
    })
  },

  removeDraft() {
    wx.removeStorageSync('sellShopData')
  },

  touchmove() {
    // 空函数 防止滚动
  },

  init() {
    this.getDistrictList()
    this.getTransferWay()
    this.getAdvantageList()
    this.getArea()
  }
})
